import 'dart:math';

import 'package:decimal/decimal.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:ls_work/res/colors.dart';
// import 'package:syncfusion_flutter_charts/charts.dart';
// import 'package:yyt_work_app_flutter/res/color_res.dart';

class StaticsChatBarWidget {
  ///折线图
  static LineChart createLineChat(List<FlSpot> spots,
      {num maxX = 12,
      double interval = 4,
      String tipsTitle = "",
      List<FlSpot>? extraSpots,
      String extraTips = "",
      Color? mainColor,
      Color extraColor = Colors.red}) {
    var lineDatas = [
      LineChartBarData(
          spots: spots,
          color: mainColor ?? Colours.app_main,
          barWidth: 1,
          dotData:
              FlDotData(getDotPainter: (FlSpot, double, LineChartBarData, int) {
            return FlDotCirclePainter(
                radius: 3,
                color: mainColor ?? Colours.app_main,
                strokeWidth: 0);
          }),
          isStrokeCapRound: true)
    ];
    if (extraSpots != null && extraSpots.isNotEmpty) {
      lineDatas.add(LineChartBarData(
          spots: extraSpots,
          color: extraColor,
          barWidth: 1,
          dotData:
              FlDotData(getDotPainter: (FlSpot, double, LineChartBarData, int) {
            return FlDotCirclePainter(
                radius: 3, color: extraColor, strokeWidth: 0);
          }),
          isStrokeCapRound: true));
    }

    return LineChart(LineChartData(
        lineBarsData: lineDatas,
        maxX: maxX.toDouble(),
        minY: interval == 0 ? 0 : null,
        backgroundColor: Colors.white,
        borderData: FlBorderData(border: Border(bottom: BorderSide())),
        gridData: FlGridData(
            horizontalInterval: interval == 0 ? null : interval,
            getDrawingHorizontalLine: (value) {
              return FlLine(
                  dashArray: [3], strokeWidth: 1, color: Colors.grey[300]);
            }),
        lineTouchData: LineTouchData(
            enabled: true,
            touchTooltipData: LineTouchTooltipData(
                getTooltipItems: (List<LineBarSpot> touchedSpots) {
              return touchedSpots.map((e) {
                var item = spots[e.spotIndex];
                return LineTooltipItem(
                    "${(item.x + 1).toInt()}月 ${e.barIndex == 0 ? tipsTitle : extraTips}:${Decimal.parse(item.y.toString()).toString()}",
                    TextStyle(
                        color: e.barIndex == 0
                            ? mainColor ?? Colours.app_main
                            : extraColor));
              }).toList();
            }),
            getTouchedSpotIndicator:
                (LineChartBarData barData, List<int> spotIndexes) {
              return [
                TouchedSpotIndicatorData(
                  FlLine(strokeWidth: 1, color: Colours.app_main),
                  FlDotData(),
                )
              ];
            }),
        titlesData: FlTitlesData(
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                  showTitles: true,
                  getTitlesWidget: (value,meta){
                    var str = "";
                    if ((value + 1).toInt() >= 13) {
                      str =  '';
                    } else {
                      str = "${(value + 1).toInt().toString()}月";
                    }
                    return Text(str);
                  },
            )),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                  showTitles: true,
                  interval: interval == 0 ? null : interval,
                  getTitlesWidget: (value,meta){
                    return Text(Decimal.parse(value.toString()).toString());
    }
            )

            )
        )
    ));
  }

  ///柱状图
  static BarChart createSingleBarChat(List<BarData> data,
      {double interval = 4, String tipsTitle = "", double barWidth = 30}) {
    return BarChart(
      BarChartData(
          barGroups: data.map((e) {
            return BarChartGroupData(x: e.x, barRods: [
              BarChartRodData(
                  toY: e.value,
                  width: barWidth,
                  borderRadius: BorderRadius.circular(0))
            ]);
          }).toList(),
          alignment: BarChartAlignment.spaceAround,
          backgroundColor: Colors.white,
          borderData: FlBorderData(border: Border(bottom: BorderSide())),
          gridData: FlGridData(
              horizontalInterval: interval == 0 ? null : interval,
              getDrawingHorizontalLine: (value) {
                return FlLine(
                    dashArray: [3], strokeWidth: 1, color: Colors.grey[300]);
              }),
          barTouchData: BarTouchData(
            enabled: true,
            touchTooltipData: BarTouchTooltipData(getTooltipItem:
                (BarChartGroupData group, int groupIndex, BarChartRodData rod,
                    int rodIndex) {
              var item = data[groupIndex];
              return BarTooltipItem(
                  "${item.name} ${tipsTitle}:${Decimal.parse(item.value.toString()).toString()}",
                  TextStyle(color: Colours.app_main));
            }),
          ),
          titlesData: FlTitlesData(
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value,meta) {
                      var str = "";
                      if (value > data.length) {
                        str =  '';
                      } else {
                        str =  data[value.toInt()].name;
                      }
                      return Text(str);
                    })
              ),
              leftTitles:AxisTitles(
                sideTitles:  SideTitles(
                    showTitles: true,
                    interval: interval == 0 ? null : interval,
                    getTitlesWidget: (value, meta) {
                      return Text(Decimal.parse(value.toString()).toString());
                    })
              ))),
    );
  }

  // static SfCartesianChart createBarChart(List<XyDataSeries> datas,
  //     {List<Color>? palette, double? max, bool isVisible = true}) {
  //   return SfCartesianChart(
  //       backgroundColor: Colors.white,
  //       palette: palette ??
  //           [Color(0xff6699ff), Color(0xFF66D46B), Color(0xFFFDDD12)],
  //       primaryXAxis: CategoryAxis(),
  //       primaryYAxis: NumericAxis(axisLine: AxisLine(width: 0), maximum: max),
  //       // Enable legend
  //       legend: Legend(isVisible: isVisible, position: LegendPosition.top),
  //       tooltipBehavior: TooltipBehavior(
  //         enable: true,
  //       ),
  //       series: datas);
  // }

  // static changeToStackBarChartData(List<ChartData> datas) {
  //   return datas.map((e) {
  //     return StackedBarSeries<SalesData, String>(
  //         // Bind data source
  //         name: e.groupName,
  //         width: 0.5,
  //         dataSource: e.datas ?? [],
  //         xValueMapper: (SalesData sales, _) => sales.name,
  //         yValueMapper: (SalesData sales, _) => sales.value);
  //   }).toList();
  // }

  // static changeToColumnChartData(List<ChartData> datas,{double space = 0}) {
  //   return datas.map((e) {
  //     return ColumnSeries<SalesData, String>(
  //         // Bind data source
  //         name: e.groupName,
  //         dataSource: e.datas ?? [],
  //         spacing: space,
  //         xValueMapper: (SalesData sales, _) => sales.name,
  //         yValueMapper: (SalesData sales, _) => sales.value);
  //   }).toList();
  // }
  //
  // static changeToBarChartData(List<ChartData> datas,{double space = 0}) {
  //   return datas.map((e) {
  //     return BarSeries<SalesData, String>(
  //       // Bind data source
  //         name: e.groupName,
  //         dataSource: e.datas ?? [],
  //         spacing: space,
  //         xValueMapper: (SalesData sales, _) => sales.name,
  //         yValueMapper: (SalesData sales, _) => sales.value);
  //   }).toList();
  // }


  static Widget pieBar(PieData data) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          decoration: BoxDecoration(
            color: data.color,
            shape: BoxShape.circle,
          ),
          width: 8,
          height: 8,
        ),
        SizedBox(
          width: 7,
        ),
        CommonText(data.title, textSize: 12).setWeight(4),
        SizedBox(
          width: 7,
        ),
        CommonText("${Decimal.parse(data.percent.toString()).toString()}%",
                textSize: 12)
            .setWeight(2),
        SizedBox(
          width: 7,
        ),
        CommonText(Decimal.parse(data.value.toString()).toString(),
                textSize: 12)
            .setWeight(1),
      ],
    );
  }
}

class ChartData {
  final String groupName;
  List<SalesData>? datas;

  ChartData(this.groupName, {this.datas});
}

class SalesData {
  SalesData(this.name, this.value);

  final String name;
  final double value;
}

///饼图
class PieChartWidget extends StatefulWidget {
  final double pieWidth;
  final bool showTitle;
  final List<PieData> data;
  final double centerRadius;
  bool isEmptyData;

  PieChartWidget(this.data,
      {this.pieWidth = 50,this.centerRadius = 20, this.showTitle = true, this.isEmptyData = true});

  @override
  State<StatefulWidget> createState() => _PieChartState();
}

class _PieChartState extends State<PieChartWidget> {
  int touchedIndex = -1;

  @override
  void initState() {
    super.initState();
    setState(() {
      var list = widget.data.map((e) {
        return e.value;
      }).toList();
      var minv = list.reduce((value, element) => min(value, element));
      var maxv = list.reduce((value, element) => max(value, element));
      if (minv == 0 && maxv == 0) {
        widget.isEmptyData = true;
      } else {
        widget.isEmptyData = false;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.data.isEmpty
        ? Container()
        : PieChart(PieChartData(
            sections: List.generate(widget.data.length, (index) {
              final isTouched = index == touchedIndex;
              final opacity = isTouched ? 0.8 : 1.0;
              final double scale = isTouched ? 1.15 : 1.0;
              var item = widget.data[index];
              return PieChartSectionData(
                  value: (widget.isEmptyData || widget.data.isEmpty)
                      ? 1
                      : item.value,
                  radius: widget.pieWidth * scale,
                  // title: item.title.isEmpty ? null : item.title,
                  color: item.color.withOpacity(opacity),
                  badgeWidget: isTouched
                      ? CommonText(
                              "${item.title}:${Decimal.parse(item.value.toString())}",
                              textColor: Colors.white)
                          .addToContainer(
                              decoration: BoxDecoration(
                                  color: Color(0x90000000),
                                  borderRadius: BorderRadius.circular(4)),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 6))
                      : null,
                  title: '${item.percent.roundToDouble()}%\n${item.title}',
                  titleStyle: TextStyle(color: Colors.white),
                  showTitle: widget.showTitle);
            }),
            centerSpaceRadius: widget.centerRadius,
            borderData: FlBorderData(
              show: false,
            ),
            pieTouchData: PieTouchData(
                enabled: true,
                touchCallback: (event, pieTouchResponse,) {
                  setState(() {

                    if (
                        pieTouchResponse?.touchedSection != null) {
                      touchedIndex =
                          pieTouchResponse?.touchedSection?.touchedSectionIndex??0;
                    } else {
                      touchedIndex = -1;
                    }
                  });
                })));
  }
}

class BarData {
  final int x;
  final String name;
  final double value;
  final String tips;

  BarData(this.x, this.name, this.value, {this.tips = ""});
}

class PieData {
  final double value;
  final Color color;
  final String title;
  final num percent;

  PieData(this.value, this.color, this.percent, {this.title = ""});
}

/// Sample ordinal data type.
class OrdinalSales {
  final String year;
  final int sales;

  OrdinalSales(this.year, this.sales);
}
